import Vue from "vue";
import VueRouter from "vue-router";
//导入路由表
import routes from "./routes";
//导入仓库
import store from "@/store";

//使用插件：调用install方法，使Vue的实例上有$router属性
Vue.use(VueRouter);

//封装push、replace方法
const originPush = VueRouter.prototype.push;
const originReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function (location, onComplete, onAbort) {
  if (onComplete === undefined && onAbort === undefined) {
    //说明只传了location，当路径重复，会报错
    //this是实例,报错被catch的回调处理,返回promise对象
    return originPush.call(this, location, onComplete, onAbort).catch(() => {});
  }
  return originPush.call(this, location, onComplete, onAbort);
};
VueRouter.prototype.replace = function (location, onComplete, onAbort) {
  if (onComplete === undefined && onAbort === undefined) {
    return originReplace
      .call(this, location, onComplete, onAbort)
      .catch(() => {});
  }
  return originReplace.call(this.location, onComplete, onAbort);
};

//建路由器
const router = new VueRouter({
  routes,
  // scrollBehavior (to, from, savedPosition) {
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
});

//全局前置守卫
//校验token，读取用户数据
router.beforeEach(async (to, from, next) => {
  //token和userInfo在vuex里
  let token = store.state.user.token;
  let userInfo = store.state.user.userInfo;
  //判断token
  if (token) {
    //先判断不是再去登录页
    if (to.path !== "/login") {
      //再判断用户数据
      if (userInfo.name) {
        next();
      } else {
        //发送token获取用户数据
        try {
          await store.dispatch('user/getUserInfo');
          next()
        } catch (error) {
          //说明token无效了
          //清空token和userInfo（action、mutation），重新跳转登录页
          store.dispatch('user/reset');
          router.push('/login');
        }
       

      }
    } else {
      //返回home页
      next("/");
    }
  } else {
    //没有token，有些页面不能去
    let path = to.path;
    if(path.startsWith('/pay') || path.startsWith('/center') || path.startsWith('/trade')) {
      router.push('/login?redirect=' + path);
    } else {
      next();
    }
   
  }
});

//默认暴露
export default router;
